window.onload = function () {
  const worker = new SharedWorker('shareworker.js')
  const musics = document.querySelectorAll('.music')
  const statusEl = document.getElementById('status')
  let playerWindowOpened = false

  musics.forEach(music => {
    music.addEventListener('click', e => {
      if (!playerWindowOpened) {
        window.open('./player.html', 'musicPlayer')
        playerWindowOpened = true
      }
      const musicId = e.target.dataset.id
      worker.port.postMessage({type: 'switch', music: musicId})
    })
  })

  worker.port.start()

  worker.port.onmessage = e => {
    if (e.data.type === 'play') {
      const musicName = e.data.music.split('/').pop()
      statusEl.textContent = `播放器正在播放: ${musicName}`
    }
  }
}
